import isPlainObject from 'lodash/isPlainObject';

type ObjectArray = { key: string; value: any }[];
type PlainObject = { [key: string]: any };

export const convertObjToArray = (obj: PlainObject): ObjectArray => {
  return Object.keys(obj).reduce((acc: ObjectArray, key: string) => {
    acc.push({ key, value: obj[key] });
    return acc;
  }, []);
};

export const isAnomaly = (value: any) => ['', null].includes(value);

const hasAnomalyData = (data: any): boolean => {
  if (!isPlainObject(data)) {
    return isAnomaly(data);
  }
  return Object.keys(data).some((key: string) => {
    const value = data[key];
    return hasAnomalyData(value);
  });
};

// null 和 '' 为异常值
export const filterOutAnomalyData = (obj: PlainObject, result = {}): PlainObject => {
  Object.keys(obj).forEach(key => {
    const value = obj[key];
    if (isPlainObject(value) && hasAnomalyData(value)) {
      result[key] = {};
      filterOutAnomalyData(value, result[key]);
    } else {
      if (isAnomaly(value)) {
        result[key] = value;
      }
    }
  });

  return result;
};
